package com.example.goodpet.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.example.goodpet.R;
import com.example.goodpet.activity.adapter.PetInfoImageAdapter;
import com.example.goodpet.bean.Follow;
import com.example.goodpet.commentdialog.bean.CommentEntity;
import com.example.goodpet.commentdialog.bean.CommentMoreBean;
import com.example.goodpet.commentdialog.bean.FirstLevelBean;
import com.example.goodpet.commentdialog.bean.GoodpetCommentFirst;
import com.example.goodpet.commentdialog.bean.GoodpetCommentSecond;
import com.example.goodpet.commentdialog.bean.SecondLevelBean;
import com.example.goodpet.commentdialog.dialog.InputTextMsgDialog;
import com.example.goodpet.commentdialog.listener.SoftKeyBoardListener;
import com.example.goodpet.commentdialog.multi.CommentDialogAdapter;
import com.example.goodpet.commentdialog.util.RecyclerViewUtil;
import com.example.goodpet.db.dao.GoodpetHistoryDAO;
import com.example.goodpet.db.entity.GoodpetHistory;
import com.example.goodpet.bean.PetCollect;
import com.example.goodpet.bean.ResponseBody;
import com.example.goodpet.bean.UserPetInfo;
import com.example.goodpet.chat.activity.ChatActivity;
import com.example.goodpet.common.EndlessRecyclerOnScrollListener;
import com.example.goodpet.common.LoadMoreWrapper;
import com.example.goodpet.db.DatabaseHelper;
import com.example.goodpet.db.dao.UserDAO;
import com.example.goodpet.db.entity.User;
import com.example.goodpet.home.homeRecommend.adapter.RecommendRecycleViewAdapter;
import com.example.goodpet.service.HomeService;
import com.example.goodpet.service.PetInformationService;
import com.example.goodpet.service.UserService;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.Constants;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.TimeSeed;
import com.example.goodpet.utils.SecurityUtils;
import com.example.goodpet.utils.UIUtils;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class PetInfoActivity extends FragmentActivity implements View.OnClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    private final String TAG = this.getClass().getSimpleName();
    private TextView tvSearch;
    private ImageButton ibPetInfoBack;
    private ImageButton ibPetInfoMore;
    private CircleImageView ivPetInfoReleasePortrait;
    private TextView tvPetInfoReleaseUser;
    private TextView tvPetInfoReleaseTime;
    private TextView btnPetInfoFocus;
    private RecyclerView petInfoImage;
    private TextView tvPetInfoDesc;
    private TextView tvSearchHome;
    private LinearLayout llPetsRoot;
    private TextView tvPetInfoLiuyan;
    private TextView tvPetInfoCollection;
    private Button btnPetInfoConsult;
    private TextView tvMoreShare;
    private TextView tvMoreMessage;
    private TextView tvMoreFavorites;
    private Button btnMore;
    private RecyclerView rvPetInfoMore;
    private TextView tvPetInfoLocation;
    private UserPetInfo userPetInfo;

    private int PAGE;
    private int[] page=new int[0];
    private int SIZE=10;
    private static final String PET_INFO = "petInfo";
    private static final String RECOMMEND_INFO = "recommendInfo";

    private  boolean isCollect=false;
    private  boolean isFollow=false;

    private Retrofit retrofit;
    private HomeService homeService;
    private PetInformationService petInformationService;
    private UserService userService;
    private long seed= TimeSeed.Get();
    private UserDAO userDAO;
    private GoodpetHistoryDAO goodpetHistoryDAO;

    private List<UserPetInfo> userPetInfos;
    //VLayout
    private VirtualLayoutManager layoutManager;
    //主页上方适配器集合
    private List<DelegateAdapter.Adapter> subAdapters = new LinkedList();

    private List<MultiItemEntity> data = new ArrayList<>();
    private List<FirstLevelBean> datas = new ArrayList<>();
    private BottomSheetDialog bottomSheetDialog;
    private InputTextMsgDialog inputTextMsgDialog;
    private float slideOffset = 0;
    private CommentDialogAdapter bottomSheetAdapter;
    private RecyclerView rv_dialog_lists;
    private long totalCount = 0;
    private int offsetY;
    private int positionCount = 0;
    private RecyclerViewUtil mRecyclerViewUtil;
    private SoftKeyBoardListener mKeyBoardListener;

//    private Map<String,Integer> mapPage=new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pet_info);
        findViews();
        UltimateBarX.statusBarOnly(this)
                .fitWindow(true)
                .colorRes(R.color.ic_back_background)
                .light(true)
                .apply();
        ActivityManager.getInstance().addActivity(this);
        retrofit = RetrofitSingleton.getRetrofitConstance();
        homeService = retrofit.create(HomeService.class);
        userService=retrofit.create(UserService.class);
        petInformationService=retrofit.create(PetInformationService.class);


        //接受主页传来的数据
        userPetInfo=getIntent().getParcelableExtra("userPetInfo");

        //Log.e(TAG, "onCreate: "+pet );
        if(userPetInfo !=null){
//            Toast.makeText(this, "petsBean"+pet.getPlace(), Toast.LENGTH_SHORT).show();
            setDataForView(userPetInfo);
            //初始化留言数据
            mRecyclerViewUtil = new RecyclerViewUtil();
        }
        if (MyApplication.user!=null && userPetInfo!=null){
            initCommentData();
        }
        initMoreRecommend(userPetInfo);
        if (MyApplication.user!=null) {
            //初始化界面
            initViewStatus();
            //记录历史信息
            recordHistory();
        }
        //记录或更新该页面展示的用户在本地数据库中的信息
        recordUser();

    }

    private void initRefresh() {
        PAGE=1;
        datas.clear();
        initCommentData();
        dataSort(0);
        bottomSheetAdapter.setNewData(data);
    }

    //原始数据 一般是从服务器接口请求过来的
    private void initCommentData() {
        homeService.selectGoodpetCommentCount(userPetInfo.getPetId())
                .enqueue(new Callback<ResponseBody<Integer>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<Integer>> call, Response<ResponseBody<Integer>> response) {
                        ResponseBody<Integer> body = response.body();
                        if(body.getCode()==200){
                            totalCount=body.getData();
                            page=new int[(int) totalCount];
                            initNext();
                        }else{
                            UIUtils.toast("评论数获取失败",false);
                        }
                    }

                    private void initNext() {
                        homeService.selectGoodpetComment(MyApplication.user.getId(),userPetInfo.getPetId(),1)
                                .enqueue(new Callback<ResponseBody<List<FirstLevelBean>>>() {
                                    @Override
                                    public void onResponse(Call<ResponseBody<List<FirstLevelBean>>> call, Response<ResponseBody<List<FirstLevelBean>>> response) {
                                        ResponseBody<List<FirstLevelBean>> body = response.body();
                                        if(body.getCode()==200){

                                            //后端需要获取除positionCount外的所有数据！！！！！！！！！！！

                                            List<FirstLevelBean> data1 = body.getData();
                                            if(null!=data1){
                                                for (FirstLevelBean datum : data1) {
                                                    page[datum.getPosition()]=1;
                                                    datum.setSecondLevelBeans(new ArrayList<>());
                                                }
                                                datas.addAll(data1);
//                                Log.e(TAG, "onResponse: "+data1);
                                            }

                                        }else{
                                            Log.e(TAG, "onResponse: "+"无评论" );
//                                                    UIUtils.toast("暂无更多评论",false);
                                        }
                                        dataSort(0);
                                        showSheetDialog();
                                    }

                                    @Override
                                    public void onFailure(Call<ResponseBody<List<FirstLevelBean>>> call, Throwable t) {
                                        UIUtils.toast("连接服务器失败",false);
                                    }
                                });
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<Integer>> call, Throwable t) {
                        UIUtils.toast("连接服务器失败",false);
                    }
                });



    }

    /**
     * 对数据重新进行排列
     * 目的是为了让一级评论和二级评论同为item
     * 解决滑动卡顿问题
     *
     * @param position
     */
    private void dataSort(int position) {

        if (datas.isEmpty()) {
            data.add(new MultiItemEntity() {
                @Override
                public int getItemType() {
                    return CommentEntity.TYPE_COMMENT_EMPTY;
                }
            });
            return;
        }

        if (position <= 0) data.clear();
        int posCount = data.size();
        int count = datas.size();
        for (int i = 0; i < count; i++) {
            if (i < position) continue;

            //一级评论
            FirstLevelBean firstLevelBean = datas.get(i);
            if (firstLevelBean == null) continue;
            firstLevelBean.setPosition(i);
            posCount += 2;
            List<SecondLevelBean> secondLevelBeans = firstLevelBean.getSecondLevelBeans();
//            Log.e(TAG, "dataSort: "+secondLevelBeans );
//
            int beanSize = secondLevelBeans.size();
            //如果当前一级评论内二级评论的数据已经获取完毕，则不需要再有更多的点击
            if (firstLevelBean.getTotalCount()==beanSize+1) {
                //如果获取完二级评论数据后，发现并没有二级评论，直接跳
                if(firstLevelBean.getTotalCount()==1){
                    firstLevelBean.setPositionCount(posCount);
                    data.add(firstLevelBean);
                    continue;
                }
            }
            //有二级评论，把数据加上去
            posCount += beanSize;
            firstLevelBean.setPositionCount(posCount);
            data.add(firstLevelBean);

            //二级评论
            for (int j = 0; j < beanSize; j++) {
                SecondLevelBean secondLevelBean = secondLevelBeans.get(j);
                secondLevelBean.setChildPosition(j);
                secondLevelBean.setPosition(i);
                secondLevelBean.setPositionCount(posCount);
                data.add(secondLevelBean);
            }
//            Log.e(TAG, "dataSort: "+beanSize );
            //展示更多的item
//            Log.e(TAG, "dataSort: "+firstLevelBean.getTotalCount() );
            if (beanSize+1 < firstLevelBean.getTotalCount()) {
                CommentMoreBean moreBean = new CommentMoreBean();
                moreBean.setPosition(i);
                moreBean.setPositionCount(posCount);
                moreBean.setTotalCount(firstLevelBean.getTotalCount());
                data.add(moreBean);
            }

        }
    }

    public void show() {
        for (int i = 0; i < page.length; i++) {
            page[i]=1;
        }
//        for(String key : mapPage.keySet()){
//            mapPage.put(key,1);
//        }
        bottomSheetAdapter.notifyDataSetChanged();
        slideOffset = 0;
        bottomSheetDialog.show();
    }


    private void showSheetDialog() {
        if (bottomSheetDialog != null) {
            return;
        }

        //view
        View view = View.inflate(this, R.layout.dialog_bottomsheet, null);
        ImageView iv_dialog_close = (ImageView) view.findViewById(R.id.dialog_bottomsheet_iv_close);
        rv_dialog_lists = (RecyclerView) view.findViewById(R.id.dialog_bottomsheet_rv_lists);
        RelativeLayout rl_comment = view.findViewById(R.id.rl_comment);
        iv_dialog_close.setOnClickListener(v -> bottomSheetDialog.dismiss());
        rl_comment.setOnClickListener(v -> {
            //添加二级评论
            initInputTextMsgDialog(null, false, null, -1);
        });

        //adapter
        bottomSheetAdapter = new CommentDialogAdapter(data);
        rv_dialog_lists.setHasFixedSize(true);
        rv_dialog_lists.setLayoutManager(new LinearLayoutManager(this));
        closeDefaultAnimator(rv_dialog_lists);
        bottomSheetAdapter.setOnLoadMoreListener(this, rv_dialog_lists);
        rv_dialog_lists.setAdapter(bottomSheetAdapter);

        //dialog
        bottomSheetDialog = new BottomSheetDialog(this, R.style.dialog);
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCanceledOnTouchOutside(true);
        BottomSheetBehavior mDialogBehavior = BottomSheetBehavior.from((View) view.getParent());
        mDialogBehavior.setPeekHeight(getWindowHeight());
        //dialog滑动监听
        mDialogBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    mDialogBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                } else if (newState == BottomSheetBehavior.STATE_SETTLING) {
                    if (slideOffset <= -0.28) {
                        //当向下滑动时 值为负数

                        bottomSheetDialog.dismiss();
                    }
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                PetInfoActivity.this.slideOffset = slideOffset;//记录滑动值
            }
        });

        initListener();
    }

    private void initListener() {

        for (int i = 0; i < page.length; i++) {
            page[i]=1;
        }
        // 点击事件
        bottomSheetAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view1, int position) {
                switch ((int) view1.getTag()) {
                    case CommentEntity.TYPE_COMMENT_PARENT:
                        if (view1.getId() == R.id.rl_group) {
                            //添加二级评论
                            PetInfoActivity.this.initInputTextMsgDialog((View) view1.getParent(), false, bottomSheetAdapter.getData().get(position), position);
                        } else if (view1.getId() == R.id.ll_like) {
                            //一级评论点赞 项目中还得通知服务器 成功才可以修改
                            FirstLevelBean bean = (FirstLevelBean) bottomSheetAdapter.getData().get(position);
                            homeService.goodpetCommentLike(MyApplication.user.getId(),bean.getId())
                                    .enqueue(new Callback<ResponseBody<Integer>>() {
                                        @Override
                                        public void onResponse(Call<ResponseBody<Integer>> call, Response<ResponseBody<Integer>> response) {
                                            ResponseBody<Integer> body = response.body();
                                            if(body.getCode()==200) {
                                                if (body.getData() > 0) {
                                                    bean.setLikeCount(bean.getLikeCount() + (bean.getIsLike() == 0 ? 1 : -1));
                                                    bean.setIsLike(bean.getIsLike() == 0 ? 1 : 0);
                                                    datas.set(bean.getPosition(), bean);
                                                    PetInfoActivity.this.dataSort(0);
                                                    bottomSheetAdapter.notifyDataSetChanged();
                                                } else {
                                                    UIUtils.toast("点赞失败", false);
                                                }
                                            }else if(body.getCode()==404){
                                                UIUtils.toast("点赞失败 404",false);
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call<ResponseBody<Integer>> call, Throwable t) {
                                            UIUtils.toast("连接服务器失败，点赞失败",false);
                                        }
                                    });

                        }
                        break;
                    case CommentEntity.TYPE_COMMENT_CHILD:

                        if (view1.getId() == R.id.rl_group) {
                            //添加二级评论（回复）
                            PetInfoActivity.this.initInputTextMsgDialog(view1, true, bottomSheetAdapter.getData().get(position), position);
                        } else if (view1.getId() == R.id.ll_like) {
                            //二级评论点赞 项目中还得通知服务器 成功才可以修改
                            SecondLevelBean bean = (SecondLevelBean) bottomSheetAdapter.getData().get(position);
                            homeService.goodpetCommentLikeSecond(MyApplication.user.getId(),bean.getId())
                                    .enqueue(new Callback<ResponseBody<Integer>>() {
                                        @Override
                                        public void onResponse(Call<ResponseBody<Integer>> call, Response<ResponseBody<Integer>> response) {
                                            ResponseBody<Integer> body = response.body();
                                            if(body.getCode()==200){
                                                if(body.getData()>0){
                                                    bean.setLikeCount(bean.getLikeCount() + (bean.getIsLike() == 0 ? 1 : -1));
                                                    bean.setIsLike(bean.getIsLike() == 0 ? 1 : 0);

                                                    List<SecondLevelBean> secondLevelBeans = datas.get((int) bean.getPosition()).getSecondLevelBeans();
                                                    secondLevelBeans.set(bean.getChildPosition(), bean);
//                            CommentMultiActivity.this.dataSort(0);
                                                    bottomSheetAdapter.notifyDataSetChanged();
                                                }else{
                                                    UIUtils.toast("点赞失败", false);
                                                }
                                            }else if(body.getCode()==404){
                                                UIUtils.toast("点赞失败 404", false);
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call<ResponseBody<Integer>> call, Throwable t) {
                                            UIUtils.toast("连接服务器失败，点赞失败",false);
                                        }
                                    });

                        }

                        break;
                    case CommentEntity.TYPE_COMMENT_MORE:
                        //在项目中是从服务器获取数据，其实就是二级评论分页获取，同样获取很多数据。。。。
                        CommentMoreBean moreBean = (CommentMoreBean) bottomSheetAdapter.getData().get(position);

                        int positon=(int) moreBean.getPosition();
                        //根据位置获取firstId
                        long firstId =  datas.get(positon).getId();
                        //根据firstId获取当前页码
//                        int page = mapPage.get(String.valueOf(id));
                        homeService.selectGoodpetCommentSecond(MyApplication.user.getId(),firstId,page[positon])
                                .enqueue(new Callback<ResponseBody<List<SecondLevelBean>>>() {
                                    @Override
                                    public void onResponse(Call<ResponseBody<List<SecondLevelBean>>> call, Response<ResponseBody<List<SecondLevelBean>>> response) {
                                        ResponseBody<List<SecondLevelBean>> body = response.body();
                                        if(body.getCode()==200){
                                            List<SecondLevelBean> data = body.getData();
                                            if(null!=data){
                                                datas.get((int) moreBean.getPosition()).getSecondLevelBeans().addAll(data);
                                                PetInfoActivity.this.dataSort(0);
                                                bottomSheetAdapter.notifyDataSetChanged();
                                            }else{
                                                UIUtils.toast("获取评论数据失败",false);
                                            }

                                        }else if(body.getCode()==404){
                                            UIUtils.toast("获取评论数据失败 404",false);
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<ResponseBody<List<SecondLevelBean>>> call, Throwable t) {
                                        UIUtils.toast("连接服务器失败，获取评论数据失败",false);
                                    }
                                });
                        page[positon]++;
//                        page++;
//                        mapPage.put(String.valueOf(id),page);
                        break;
                    case CommentEntity.TYPE_COMMENT_EMPTY:
                        PetInfoActivity.this.initRefresh();
                        break;

                }

            }
        });
        //滚动事件
        if (mRecyclerViewUtil != null) mRecyclerViewUtil.initScrollListener(rv_dialog_lists);

        mKeyBoardListener = new SoftKeyBoardListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
            }

            @Override
            public void keyBoardHide(int height) {
                dismissInputDialog();
            }
        });
    }

    private void initInputTextMsgDialog(View view, final boolean isReply, final MultiItemEntity item, final int position) {
        dismissInputDialog();
        if (view != null) {
            offsetY = view.getTop();
            scrollLocation(offsetY);
        }
        if (inputTextMsgDialog == null) {
            inputTextMsgDialog = new InputTextMsgDialog(this, R.style.dialog);
            inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() {
                @Override
                public void onTextSend(String msg) {
                    addComment(isReply, item, position, msg);
                }

                @Override
                public void dismiss() {
                    //item滑动到原位
                    scrollLocation(-offsetY);
                }
            });
        }
        showInputTextMsgDialog();
    }

    //添加评论
    private void addComment(boolean isReply, MultiItemEntity item, final int position, String msg) {
        final String userName = MyApplication.user.getNickname();
        if (position >= 0) {
            //添加二级评论
            int pos = 0;
            String replyUserName = "未知";
            long replyUserId = MyApplication.user.getId();
            if (item instanceof FirstLevelBean) {
                FirstLevelBean firstLevelBean = (FirstLevelBean) item;
                positionCount = (int) (firstLevelBean.getPositionCount() + 1);
                pos = (int) firstLevelBean.getPosition();
                replyUserName = firstLevelBean.getUserName();
                replyUserId = firstLevelBean.getUserId()==0?replyUserId:firstLevelBean.getUserId();
            } else if (item instanceof SecondLevelBean) {
                SecondLevelBean secondLevelBean = (SecondLevelBean) item;
                positionCount = (int) (secondLevelBean.getPositionCount() + 1);
                pos = (int) secondLevelBean.getPosition();
                replyUserName = secondLevelBean.getUserName();
                replyUserId = secondLevelBean.getUserId()==0?replyUserId:secondLevelBean.getUserId();
            }
                //进行服务器端的操作，将二级评论添加至数据库
                GoodpetCommentSecond goodpetCommentSecond=new GoodpetCommentSecond();
                goodpetCommentSecond.setReplyUserName(replyUserName);
                goodpetCommentSecond.setReplyUserId(replyUserId);
                goodpetCommentSecond.setIsReply(isReply ? 1 : 0);
                goodpetCommentSecond.setContent(msg);
                goodpetCommentSecond.setLikeCount(0);
                goodpetCommentSecond.setCreateTime(System.currentTimeMillis());
                goodpetCommentSecond.setSenderId(MyApplication.user.getId());
                goodpetCommentSecond.setFirstId(datas.get(pos).getId());
            int finalPos = pos;
            homeService.insertGoodpetCommentSecond(goodpetCommentSecond)
                        .enqueue(new Callback<ResponseBody<GoodpetCommentSecond>>() {
                            @Override
                            public void onResponse(Call<ResponseBody<GoodpetCommentSecond>> call, Response<ResponseBody<GoodpetCommentSecond>> response) {
                                ResponseBody<GoodpetCommentSecond> body = response.body();
                                if(body.getCode()==200){
                                    if(body.getData()!=null){
                                        UIUtils.toast("留言成功",false);
                                        initNext(body.getData());
                                    }else{
                                        UIUtils.toast("留言失败", false);
                                    }
                                }else{
                                    UIUtils.toast("留言同步失败 404", false);
                                }
                            }

                            private void initNext(GoodpetCommentSecond data2) {
                                SecondLevelBean secondLevelBean = new SecondLevelBean();
                                secondLevelBean.setReplyUserName(data2.getReplyUserName());
                                secondLevelBean.setIsReply((int) data2.getIsReply());
                                secondLevelBean.setContent(data2.getContent());
                                secondLevelBean.setHeadImg(MyApplication.user.getPortrait());
                                secondLevelBean.setCreateTime(data2.getCreateTime());
                                secondLevelBean.setIsLike(0);
                                secondLevelBean.setUserName(userName);
                                secondLevelBean.setId(data2.getId());
                                secondLevelBean.setPosition(positionCount);

                                datas.get(finalPos).getSecondLevelBeans().add(secondLevelBean);
                                PetInfoActivity.this.dataSort(0);
                                bottomSheetAdapter.notifyDataSetChanged();
                                rv_dialog_lists.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        ((LinearLayoutManager) rv_dialog_lists.getLayoutManager())
                                                .scrollToPositionWithOffset(positionCount >= data.size() - 1 ? data.size() - 1
                                                        : positionCount, positionCount >= data.size() - 1 ? Integer.MIN_VALUE : rv_dialog_lists.getHeight());
                                    }
                                }, 100);
                            }

                            @Override
                            public void onFailure(Call<ResponseBody<GoodpetCommentSecond>> call, Throwable t) {
                                UIUtils.toast("连接服务器失败，留言失败",false);
                            }
                        });


        } else {
            //添加一级评论

            //进行服务器端的操作，将一级评论添加至数据库
            GoodpetCommentFirst goodpetCommentFirst=new GoodpetCommentFirst();
            goodpetCommentFirst.setPetId(userPetInfo.getPetId());
            goodpetCommentFirst.setSenderId(MyApplication.user.getId());
            goodpetCommentFirst.setContent(msg);
            goodpetCommentFirst.setLikeCount(0);
            goodpetCommentFirst.setCreateTime(System.currentTimeMillis());
            homeService.insertGoodpetComment(goodpetCommentFirst)
                    .enqueue(new Callback<ResponseBody<GoodpetCommentFirst>>() {
                        @Override
                        public void onResponse(Call<ResponseBody<GoodpetCommentFirst>> call, Response<ResponseBody<GoodpetCommentFirst>> response) {
                            ResponseBody<GoodpetCommentFirst> body = response.body();
                            if(body.getCode()==200){
                                if(body.getData()!=null){
                                    UIUtils.toast("评论成功",false);
                                    initNext(body.getData());
                                }else{
                                    UIUtils.toast("评论失败",false);
                                }
                            }else if(body.getCode()==404){
                                UIUtils.toast("评论失败 404",false);
                            }
                        }

                        private void initNext(GoodpetCommentFirst data1) {
                            FirstLevelBean firstLevelBean = new FirstLevelBean();
                            firstLevelBean.setUserName(userName);
                            firstLevelBean.setId(data1.getId());
                            firstLevelBean.setHeadImg(MyApplication.user.getPortrait());
                            firstLevelBean.setCreateTime(data1.getCreateTime());
                            firstLevelBean.setContent(data1.getContent());
                            firstLevelBean.setLikeCount(data1.getLikeCount());
                            firstLevelBean.setSecondLevelBeans(new ArrayList<SecondLevelBean>());
                            datas.add(0, firstLevelBean);
                            PetInfoActivity.this.dataSort(0);
                            bottomSheetAdapter.notifyDataSetChanged();
                            rv_dialog_lists.scrollToPosition(0);
                        }

                        @Override
                        public void onFailure(Call<ResponseBody<GoodpetCommentFirst>> call, Throwable t) {
                            UIUtils.toast("连接服务器失败，一级评论失败",false);
                        }
                    });




        }
    }

    private void dismissInputDialog() {
        if (inputTextMsgDialog != null) {
            if (inputTextMsgDialog.isShowing()) inputTextMsgDialog.dismiss();
            inputTextMsgDialog.cancel();
            inputTextMsgDialog = null;
        }
    }

    private void showInputTextMsgDialog() {
        inputTextMsgDialog.show();
    }

    private int getWindowHeight() {
        Resources res = getResources();
        DisplayMetrics displayMetrics = res.getDisplayMetrics();
        return displayMetrics.heightPixels;
    }

    @Override
    public void onLoadMoreRequested() {
        if (datas.size() >= totalCount) {
            bottomSheetAdapter.loadMoreEnd(false);
            return;
        }
        homeService.selectGoodpetComment(MyApplication.user.getId(), userPetInfo.getPetId(),++PAGE)
                .enqueue(new Callback<ResponseBody<List<FirstLevelBean>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<FirstLevelBean>>> call, Response<ResponseBody<List<FirstLevelBean>>> response) {
                        ResponseBody<List<FirstLevelBean>> body = response.body();
                        if(body.getCode()==200){
                            List<FirstLevelBean> data = body.getData();
                            if(null!=data){
                                for (FirstLevelBean datum : data) {
//                                    String s = String.valueOf(datum.getId());
//                                    mapPage.put(s,1);
                                    datum.setSecondLevelBeans(new ArrayList<>());
                                }
                                datas.addAll(data);
                            }
                            dataSort(datas.size() - SIZE);
                            bottomSheetAdapter.notifyDataSetChanged();
                            bottomSheetAdapter.loadMoreComplete();
                        }else if(body.getCode()==404){
                            UIUtils.toast("没有更多评论啦~",false);
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<FirstLevelBean>>> call, Throwable t) {
                        UIUtils.toast("连接服务器失败，获取评论失败",false);
                    }
                });
    }

    // item滑动
    public void scrollLocation(int offsetY) {
        try {
            rv_dialog_lists.smoothScrollBy(0, offsetY);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭默认局部刷新动画
     */
    public void closeDefaultAnimator(RecyclerView mRvCustomer) {
        if (null == mRvCustomer) return;
        mRvCustomer.getItemAnimator().setAddDuration(0);
        mRvCustomer.getItemAnimator().setChangeDuration(0);
        mRvCustomer.getItemAnimator().setMoveDuration(0);
        mRvCustomer.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) mRvCustomer.getItemAnimator()).setSupportsChangeAnimations(false);
    }

    @Override
    protected void onDestroy() {
        if (mRecyclerViewUtil != null){
            mRecyclerViewUtil.destroy();
            mRecyclerViewUtil = null;
        }
        if (mKeyBoardListener != null) {
            mKeyBoardListener.setOnSoftKeyBoardChangeListener(null);
            mKeyBoardListener = null;
        }
        bottomSheetAdapter = null;
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MyApplication.user!=null)initViewStatus();
    }

    /**
     * 记录user到sqlite数据库
     */
    private void recordUser() {
        userDAO = DatabaseHelper.getInstance(this).getUserDAO();
        User user = new User(userPetInfo.getUserId(),userPetInfo.getPhoneNumber(),userPetInfo.getNickname(),userPetInfo.getPortrait(),(int)userPetInfo.getGender(),userPetInfo.getSignature());
        userDAO.insert(user);
    }

    /**
     * 记录历史浏览信息
     */
    private void recordHistory() {
        GoodpetHistoryDAO goodpetHistoryDAO = DatabaseHelper.getInstance(this).getGoodpetHistoryDAO();
        GoodpetHistory goodpetHistory = new GoodpetHistory();
        goodpetHistory.setUserId(MyApplication.user.getId());
        goodpetHistory.setPetId(userPetInfo.getPetId());
        goodpetHistory.setPostdate(new Date(System.currentTimeMillis()).toString());
        goodpetHistoryDAO.insert(goodpetHistory);
    }

    /**
     * 初始化View的状态，例如将收藏图片更改,查询关注情况
     */
    private void initViewStatus() {
        //特判是自己的情况
        if (MyApplication.user.getId()==userPetInfo.getUserId())btnPetInfoFocus.setVisibility(View.INVISIBLE);
        //向服务端发送请求
        petInformationService.initPetInfoActivity(MyApplication.user.getId(),userPetInfo.getUserId(),userPetInfo.getPetId()).enqueue(new Callback<okhttp3.ResponseBody>() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onResponse(Call<okhttp3.ResponseBody> call, Response<okhttp3.ResponseBody> response) {
                okhttp3.ResponseBody body = response.body();
                if (body!=null){
                    String json = null;
                    try {
                        json = body.string();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
                    isFollow = jsonObject.get("isFollow").getAsInt()==1;
                    isCollect=jsonObject.get("isCollect").getAsInt()==1;
                    if (isFollow){
                        btnPetInfoFocus.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
                        btnPetInfoFocus.setText("取消关注");
                        btnPetInfoFocus.setTextColor(getColor(R.color.gray));
                    }else {
                        btnPetInfoFocus.setText("关注");
                    }
                    if (isCollect){
                        tvPetInfoCollection.setCompoundDrawablesWithIntrinsicBounds(null, getDrawable(R.drawable.collection_al), null, null);
                    }
                }
            }

            @Override
            public void onFailure(Call<okhttp3.ResponseBody> call, Throwable t) {
                UIUtils.toast("连接服务器失败",false);
                t.printStackTrace();
            }
        });
    }


    /**
     * Find the Views in the layout<br />
     * <br />
     * Auto-created on 2022-08-20 17:42:44 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    private void findViews() {
        rvPetInfoMore = findViewById(R.id.rv_pet_info_more);
        tvPetInfoLocation = findViewById(R.id.tv_pet_info_location);
        btnMore = findViewById(R.id.btn_more);
        tvMoreShare = findViewById(R.id.tv_more_share);
        tvMoreMessage = findViewById(R.id.tv_more_message);
        tvMoreFavorites = findViewById(R.id.tv_more_favorites);
        ibPetInfoBack = (ImageButton)findViewById( R.id.ib_pet_info_back );
        ibPetInfoMore = (ImageButton)findViewById( R.id.ib_pet_info_more );
        ivPetInfoReleasePortrait = (CircleImageView)findViewById( R.id.iv_pet_info_releasePortrait );
        tvPetInfoReleaseUser = (TextView)findViewById( R.id.tv_pet_info_releaseUser );
        tvPetInfoReleaseTime = (TextView)findViewById( R.id.tv_pet_info_releaseTime );
        btnPetInfoFocus = (TextView)findViewById( R.id.btn_pet_info_focus );
        petInfoImage = findViewById(R.id.petInfoImage);
        tvPetInfoDesc = (TextView)findViewById( R.id.tv_pet_info_desc );
        tvSearchHome = (TextView)findViewById( R.id.tv_search_home );
        llPetsRoot = (LinearLayout)findViewById( R.id.ll_pets_root );
        tvPetInfoLiuyan = (TextView)findViewById( R.id.tv_pet_info_liuyan );
        tvPetInfoCollection = (TextView)findViewById( R.id.tv_pet_info_collection );
        btnPetInfoConsult = (Button)findViewById( R.id.btn_pet_info_consult );
        tvSearch=findViewById(R.id.tv_pet_info_search);

        ibPetInfoBack.setOnClickListener( this );
        ibPetInfoMore.setOnClickListener( this );
        btnPetInfoConsult.setOnClickListener( this );
        btnPetInfoFocus.setOnClickListener( this );
        ivPetInfoReleasePortrait.setOnClickListener( this );
        tvPetInfoLiuyan.setOnClickListener( this );
        tvPetInfoCollection.setOnClickListener( this );
        tvMoreShare.setOnClickListener( this );
        tvMoreMessage.setOnClickListener( this );
        tvMoreFavorites.setOnClickListener( this );
        btnMore.setOnClickListener( this );
        tvSearch.setOnClickListener(this);
    }

    /**
     * Handle button click events<br />
     * <br />
     * Auto-created on 2022-08-20 17:42:44 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    @Override
    public void onClick(View v) {
        if ( v == ibPetInfoBack ) {
            // Handle clicks for ibGoodInfoBack
            finish();
        } else if ( v == ibPetInfoMore ) {
            // Handle clicks for ibPetInfoMore
            Toast.makeText(this, "更多", Toast.LENGTH_SHORT).show();
        } else if ( v == btnPetInfoConsult ) {
            // Handle clicks for btnPetInfoConsult
            if (MyApplication.user==null) actionToLoginAC();
            else {
                ChatActivity.actionStart(this, SecurityUtils.encryptPhoneNumber(userPetInfo.getPhoneNumber()),1);
            }

            //Toast.makeText(this, "在线咨询", Toast.LENGTH_SHORT).show();
        } else if ( v == btnPetInfoFocus ) {
            //关注卖家
            if (MyApplication.user==null) actionToLoginAC();
            else {
                JudgeFollowRequest();
            }
        } else if ( v == ivPetInfoReleasePortrait ) {
            // Handle clicks for btnPetInfoConsult，进入用户主页
            if (MyApplication.user==null) actionToLoginAC();
            else {
                Intent intent = new Intent(this, UserInfoActivity.class);
                intent.putExtra("user",userPetInfo);
                startActivity(intent);
            }
        } else if ( v == tvPetInfoLiuyan ) {
            // Handle clicks for btnPetInfoConsult
            if (MyApplication.user==null) actionToLoginAC();
            else{
                //打开留言列表
                PAGE=1;
                show();
            }

        } else if ( v == tvPetInfoCollection ) {
            //收藏
            // Handle clicks for btnPetInfoConsult
            if (MyApplication.user==null) actionToLoginAC();
            else {
                judgeCollectRequest();
            }
        } else if ( v == tvMoreShare ) {
            // Handle clicks for btnPetInfoConsult
            Toast.makeText(this, "分享商品信息", Toast.LENGTH_SHORT).show();
        } else if ( v == tvMoreMessage ) {
            // Handle clicks for btnPetInfoConsult
            Toast.makeText(this, "进入消息页面", Toast.LENGTH_SHORT).show();
        } else if ( v == tvMoreFavorites ) {
            // Handle clicks for btnPetInfoConsult
            Toast.makeText(this, "进入收藏页面", Toast.LENGTH_SHORT).show();
        } else if ( v == btnMore ) {
            // Handle clicks for btnPetInfoConsult
            Toast.makeText(this, "退出更多", Toast.LENGTH_SHORT).show();
        }else if (v==tvSearch){
            Intent intent=new Intent(PetInfoActivity.this, SearchActivity.class);
            intent.putExtra("type",1);
            startActivity(intent);
        }
    }



    /**
     * 设置数据
     *
     * @param userPetInfo
     */
    private void setDataForView(UserPetInfo userPetInfo) {
        //初始化该宠物所有照片
        initPetImage();

        //初始化发布者信息
        Glide.with(PetInfoActivity.this)
                .load(Constants.BASE_URL_IMAGE+userPetInfo.getPortrait())
                .into(ivPetInfoReleasePortrait);

        tvPetInfoReleaseUser.setText(userPetInfo.getNickname());
        tvPetInfoDesc.setText(userPetInfo.getOverview());
        tvPetInfoReleaseTime.setText("发布于"+userPetInfo.getPostdate());
        tvPetInfoLocation.setText("于"+userPetInfo.getPlace());
    }


    @SuppressLint("ClickableViewAccessibility")
    private void initPetImage() {
        //System.out.println("PetInfoActivity.initPetImage"+userPetInfo);
//        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 1);
        LinearLayoutManager layoutManager=new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.HORIZONTAL);
        PetInfoImageAdapter petInfoImageAdapter = new PetInfoImageAdapter(userPetInfo.getPetImage(),this);
        petInfoImage.setAdapter(petInfoImageAdapter);
        petInfoImage.setLayoutManager(layoutManager);
//        List<String> arrayList=new ArrayList<>();
//        int index=0;
//        float touchDownX;
//        float touchUpX;
//        homeService.selectImageByPetId(pet.getId())
//                .enqueue(new Callback<GoodPetImageData>() {
//                    @Override
//                    public void onResponse(Call<GoodPetImageData> call, Response<GoodPetImageData> response) {
//                        GoodPetImageData body1 = response.body();
////                Log.e(TAG, "onResponse1: "+body1);
//                        if (body1.isSuccess()){
////                    Log.e(TAG, "onResponse1: "+Constants.BASE_URL_IMAGE+body1.getData().get(0).getImageUrl());
//
//                            Glide.with(PetInfoActivity.this)
//                                    .load(Constants.BASE_URL_IMAGE+body1.getData().get(0).getImageUrl())
//                                    .into(ivPetInfoImage);
////                            List<GoodPetImage> images = body1.getData();
////                            for (int i = 0; i < images.size(); i++) {
////                                arrayList.add(Constants.BASE_URL_IMAGE+images.get(i).getImageUrl());
////                            }
//
//                        }else{
//                            UIUtils.toast("未获取到图片！",false);
//                        }
//
//                    }
//
//                    @Override
//                    public void onFailure(Call<GoodPetImageData> call, Throwable t) {
//                        UIUtils.toast("网络通信失败0",false);
//                    }
//                });

    }

    /**
     * 初始化更多页面
     * @param userPetInfo
     */
    private void initMoreRecommend(UserPetInfo userPetInfo) {
        homeService.selectAllUserPetInfo(seed,1)
                .enqueue(new Callback<ResponseBody<List<UserPetInfo>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<UserPetInfo>>> call, Response<ResponseBody<List<UserPetInfo>>> response) {
                        ResponseBody<List<UserPetInfo>> body = response.body();
                        if (body.getCode() == 200) {
                            userPetInfos = body.getData();
                            /**
                             * 鸡肋的在更多页面去除当前页面显示的宠物信息
                             */
                            for (int i = 0; i < userPetInfos.size(); i++) {
                                if (userPetInfos.get(i).getPetId() == userPetInfo.getPetId()) {
                                    userPetInfos.remove(i);
                                    break;
                                }
                            }
                            initAdapter();
                        } else {
                            UIUtils.toast("获取更多失败", false);
                        }

                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<UserPetInfo>>> call, Throwable t) {
                        UIUtils.toast("连接服务器失败", false);
                    }


                    private void initAdapter() {
                        //1.设置总布局管理器
                        layoutManager = new VirtualLayoutManager(PetInfoActivity.this);
                        rvPetInfoMore.setLayoutManager(layoutManager);
                        //2.设置回收池大小（相同类型的View可以复用，防止多次创建ItemView）
                        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
                        viewPool.setMaxRecycledViews(0, 10);
                        rvPetInfoMore.setRecycledViewPool(viewPool);
                        //3.逐个设置子模块适配器
                        addPetAdapter();

                        //4.设置总适配器
                        DelegateAdapter mainAdapter = new DelegateAdapter(layoutManager, true);
                        mainAdapter.setAdapters(subAdapters);
                        rvPetInfoMore.setAdapter(mainAdapter);
                    }


                    private void addPetAdapter() {
                        GridLayoutHelper helper = new GridLayoutHelper(2);
                        RecommendRecycleViewAdapter adapter = new RecommendRecycleViewAdapter(PetInfoActivity.this, userPetInfos);
                        LoadMoreWrapper loadMoreWrapper = new LoadMoreWrapper(adapter) {
                            @Override
                            public LayoutHelper onCreateLayoutHelper() {
                                return helper;
                            }
                        };
                        subAdapters.add(loadMoreWrapper);
                        rvPetInfoMore.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
                            @Override
                            public void onLoadMore() {
                                loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING);
                                homeService.selectAllUserPetInfo(seed, ++loadMoreWrapper.page)
                                        .enqueue(new Callback<ResponseBody<List<UserPetInfo>>>() {
                                            @Override
                                            public void onResponse(Call<ResponseBody<List<UserPetInfo>>> call, Response<ResponseBody<List<UserPetInfo>>> response) {
                                                ResponseBody<List<UserPetInfo>> body1 = response.body();
                                                //Log.d(TAG, "onResponse: "+ body);
                                                if (body1.getCode() == 200) {
                                                    List<UserPetInfo> data1 = body1.getData();
                                                    userPetInfos.addAll(data1);
                                                    loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_COMPLETE);
                                                } else if (body1.getCode() == 404) {
                                                    loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_END);
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ResponseBody<List<UserPetInfo>>> call, Throwable t) {
                                                Log.e(TAG, "onFailure: "+t.getMessage());
                                                UIUtils.toast("连接服务器失败", false);
                                            }
                                        });
                            }
                        });


                    }
                });
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }


    /**
     * 判断应该发送关注请求请求还是取消关注请求，并发送请求
     */
    private void JudgeFollowRequest() {
        if (isFollow){
            new AlertDialog.Builder(this)
                    .setTitle("温馨提示")
                    .setMessage("您确定要取消关注吗？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //连接服务器,传送用户id
                            userService.unFollowSomeone(new Follow(0, MyApplication.user.getId(),userPetInfo.getUserId(), null)).enqueue(new Callback<com.example.goodpet.bean.ResponseBody<Object>>() {
                                @Override
                                public void onResponse(Call<com.example.goodpet.bean.ResponseBody<Object>> call, Response<com.example.goodpet.bean.ResponseBody<Object>> response) {
                                    com.example.goodpet.bean.ResponseBody<Object> body = response.body();
                                    if (body!=null){
                                        int code = body.getCode();
                                        if (code==200){
                                            isFollow=false;
                                            btnPetInfoFocus.setText("关注");
                                        }else if (code==500){
                                            UIUtils.toast("服务器发生错误",false);
                                        }
                                    }
                                }

                                @Override
                                public void onFailure(Call<com.example.goodpet.bean.ResponseBody<Object>> call, Throwable t) {
                                    UIUtils.toast("连接服务器失败",false);
                                }
                            });

                        }
                    })
                    .setNegativeButton("点错了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .setCancelable(false).show();
        }else if (!isFollow){
            userService.followSomeone(new Follow(0, MyApplication.user.getId(),userPetInfo.getUserId(), new Date(System.currentTimeMillis()))).enqueue(new Callback<com.example.goodpet.bean.ResponseBody<Object>>() {
                @Override
                public void onResponse(Call<com.example.goodpet.bean.ResponseBody<Object>> call, Response<com.example.goodpet.bean.ResponseBody<Object>> response) {
                    com.example.goodpet.bean.ResponseBody<Object> body = response.body();
                    if (body!=null){
                        int code = body.getCode();
                        if (code==200){
                            btnPetInfoFocus.setText("已关注");
                            isFollow=true;
                        }else if (code==500){
                            UIUtils.toast("服务器发生错误",false);
                        }
                    }
                }

                @Override
                public void onFailure(Call<com.example.goodpet.bean.ResponseBody<Object>> call, Throwable t) {
                    UIUtils.toast("连接服务器失败",false);
                }
            });
        }
    }
    /**
     * 判断应该发送收藏请求还是取消收藏请求，并发送请求
     */
    private void judgeCollectRequest(){
        if (isCollect){
            //发送取消收藏请求
            userService.deletePetCollect(MyApplication.user.getId(),userPetInfo.getPetId()).enqueue(new Callback<ResponseBody<String>>() {
                @Override
                public void onResponse(Call<ResponseBody<String>> call, Response<ResponseBody<String>> response) {
                    ResponseBody<String> body = response.body();
                    UIUtils.toast(body.getData(), false);
                    tvPetInfoCollection.setCompoundDrawablesWithIntrinsicBounds(null,getDrawable(R.drawable.collection),null,null);
                    isCollect=false;
                }

                @Override
                public void onFailure(Call<ResponseBody<String>> call, Throwable t) {
                    UIUtils.toast("连接服务器失败",false);
                }
            });
        }else {
            // 发送收藏请求
            userService.petCollect(new PetCollect(0,MyApplication.user.getId(),userPetInfo.getPetId(),new Date(System.currentTimeMillis()))).enqueue(new Callback<ResponseBody<String>>() {
                @Override
                public void onResponse(Call<ResponseBody<String>> call, Response<ResponseBody<String>> response) {
                    ResponseBody<String> body = response.body();
                    UIUtils.toast(body.getData(), false);
                    tvPetInfoCollection.setCompoundDrawablesWithIntrinsicBounds(null,getDrawable(R.drawable.collection_al),null,null);
                    isCollect=true;
                }

                @Override
                public void onFailure(Call<ResponseBody<String>> call, Throwable t) {
                    t.printStackTrace();
                    UIUtils.toast("连接服务器失败",false);
                }
            });
        }
    }

    /**
     * 当点击用户信息时才能继续操作的区域时，如果未登录跳转至登录界面
     */
    private void actionToLoginAC() {
        startActivity(new Intent(this, LoginActivity.class));
    }
}